package com.example.tool.entity

import javafx.collections.FXCollections
import javafx.scene.Node
import javafx.scene.chart.PieChart
import javafx.scene.control.Label
import javafx.scene.input.MouseEvent
import javafx.scene.layout.Pane
import javafx.scene.paint.Color

class ChartFun {

    class PieChartFun(var w: Int, var h: Int, var title: String, var data: Map<String, Double>) {

        fun buildChar(container: Pane) {
            var chart = PieChart()
            chart.title = this.title
            chart.legendSide = javafx.geometry.Side.LEFT
            var accountData = FXCollections.observableArrayList<PieChart.Data>()
            for (bucket in data) {
                val node = PieChart.Data(bucket.key, bucket.value)
                accountData.add(node)
            }
            chart.data = accountData
            chart.maxWidth = w.toDouble()
            chart.maxHeight = h.toDouble()
            container.children.addAll(chart, addToolTip(chart))
        }

        private fun addToolTip(chart: PieChart): Label {
            val caption = Label("")
            caption.textFill = Color.RED
            caption.style = "-fx-background-color: blue;-fx-font: 24 arial;"
            val totalPieValue = chart.data.stream().mapToDouble { it.pieValue }.sum()

            // Traverse items to compute total value.
            for (data in chart.data) {
                data.node.addEventHandler(MouseEvent.MOUSE_ENTERED
                ) { e: MouseEvent ->
                    val node = e.source as Node
                    node.style = "-fx-scale-shape: true;-fx-scale-x: 1.2;-fx-scale-y:1.2;-fx-scale-z:1.2"
                    val percentPieValue = data.pieValue / totalPieValue * 100
                    val message = trimZero(data.pieValue.toString()) + " (" + String.format("%.2f", percentPieValue) + "%)"
                    caption.text = message
                    caption.translateX = e.x + chart.width / 2 + 20
                    caption.translateY = e.y - chart.height / 2 - 20
                    caption.isVisible = true
                }
                data.node.addEventHandler(MouseEvent.MOUSE_EXITED) { e: MouseEvent ->
                    val node = e.source as Node
                    node.style = ""
                }
            }
            return caption
        }

        private fun trimZero(numStr: String): String {

            var arr = numStr.split(".")
            if(arr[1].startsWith("0")){
                if(arr[1].matches(Regex("0+"))){
                    return arr[0];
                }
            }
            return numStr;

        }
    }


}